package com.example.mykotilin.navigation2

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.example.mykotilin.R
import com.example.mykotilin.databinding.FragmentDonutEntryDialogBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class DonutEntryDialogFragment : BottomSheetDialogFragment() {

    private lateinit var donutEntryViewModel: DonutEntryViewModel

    private enum class EditingState {
        NEW_DONUT,
        EXISTING_DONUT
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val donutDao = DonutDatabase.getDatabase(requireContext()).donutDao()
        donutEntryViewModel = ViewModelProvider(
            this,
            DonutViewModelFactory(donutDao)
        ).get(DonutEntryViewModel::class.java)

        val binding = FragmentDonutEntryDialogBinding.bind(view)
        var donut: Donut? = null
        val args: DonutEntryDialogFragmentArgs by navArgs()
        val editingState = if (args.itemId > 0) EditingState.EXISTING_DONUT
        else EditingState.NEW_DONUT

        if (editingState == EditingState.EXISTING_DONUT) {
            donutEntryViewModel.get(args.itemId).observe(viewLifecycleOwner) { donutItem ->
                binding.name.setText(donutItem.name)
                binding.description.setText(donutItem.description)
                binding.ratingBar.rating = donutItem.rating.toFloat()
                donut = donutItem
            }
        }

        binding.doneButton.setOnClickListener {
            val context = requireContext().applicationContext
            val navController = findNavController()

            donutEntryViewModel.addData(
                donut?.id ?: 0,
                binding.name.text.toString(),
                binding.description.text.toString(),
                binding.ratingBar.rating.toInt()
            ) { actualId ->
                val arg = DonutEntryDialogFragmentArgs(actualId).toBundle()
                val pendingIntent =
                    navController.createDeepLink().setDestination(R.id.donutEntryDialogFragment)
                        .setArguments(arg)
                        .createPendingIntent()
                Notifier.postNotification(actualId, context, pendingIntent)
            }

            dismiss()
        }
        binding.cancelButton.setOnClickListener {
            dismiss()
        }

    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return FragmentDonutEntryDialogBinding.inflate(inflater, container, false).root
    }


}